<template>
  <div class="main invoice-container">
    <section>
    <el-form :model="formData" :rules="rulesBase" size="medium" ref="formBase" label-width="150px" :disabled="!canSave">
      <el-row >
        <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="订单号:" prop="orderNo">
            <el-input v-model="formData.orderNo" :disabled="true" style="width: 80%;"></el-input>
             <el-button type="primary" size="small" @click="handleGetOrder(false)" v-if="showOrder">选择</el-button>
          </el-form-item>
        </el-col>
        <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="会员名称:" prop="memberName">
            <el-input v-model="formData.memberName" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
           <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="手机号:" prop="mobile">
            <el-input v-model="formData.mobile" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
          <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="电子邮箱:" prop="email" class="email">
            <el-input v-model="formData.email" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>

        <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="发票性质:" prop="invoiceTypeTxt">
            <el-input v-model="formData.invoiceTypeTxt" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
         <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="发票抬头:" prop="invoiceTitle">
            <el-input v-model="formData.invoiceTitle" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>
        <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="发票抬头类型:" prop="invoiceTitleType">
            <el-select v-model="formData.invoiceTitleType" placeholder="请选择">
              <el-option label="个人" value="个人" ></el-option>
              <el-option label="单位" value="单位" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <div v-if="formData.invoiceTitleType === '单位'">
          <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="纳税人识别号:" prop="gmfTaxpayerIdentifyNo">
            <el-input v-model="formData.gmfTaxpayerIdentifyNo" placeholder="请输入内容"></el-input>
          </el-form-item>
         </el-col>
          <el-col  :xs="20" :md="10" :xl="10">
            <el-form-item label="银行账号:" prop="gmfBankAccount">
              <el-input v-model="formData.gmfBankAccount" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :xs="20" :md="10" :xl="10">
            <el-form-item label="开户银行:" prop="gmfOpenBank">
              <el-input v-model="formData.gmfOpenBank" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :xs="20" :md="10" :xl="10">
            <el-form-item label="注册地址:" prop="gmfRegisterAddress">
              <el-input v-model="formData.gmfRegisterAddress" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :xs="20" :md="10" :xl="10">
            <el-form-item label="注册电话:" prop="gmfRegisterPhone">
              <el-input v-model="formData.gmfRegisterPhone" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </div>
        <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="合同签约方:" prop="contractingPartyId">
           <el-select v-model="formData.contractingPartyId" placeholder="请选择">
            <el-option :label="item.contractingPartyName" :value="item.id" v-for="(item, index) in contractList" :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xl="20">
          <div class="goods-cose-contaner" >
            <div class="goods-cost-title" v-if="orderNo">商品费
              <!-- <el-button type="primary" size="mini" style="float: right;margin-right:30px;" @click="handleAddGoods">增加</el-button> -->
              <!-- <el-tooltip class="btn-s"  content="新增一张发票，商品信息" placement="left-start"> -->
               <el-button type="primary" size="mini" class="btn-s" @click="handleAddGoods" v-if="canSave">增加</el-button>
              <!-- </el-tooltip> -->
              <span style="padding: 0 50px">可开票金额:{{filtersMoney(orderPrice)}}</span>
              <span style="padding: 0 50px">已开票金额:{{totalMoney}}</span>
              <span style="padding: 0 50px">优惠金额:{{filtersMoney(formData.couponPrice)}}</span>
              <span style="padding: 0 50px">已优惠金额:{{countMoney}}</span>
            </div>
            <div class="goods-cost-table" v-for="(item, index) in formData.invoiceManualMarkRequestList" :key="index" >
              <div class="shop-info">
                <span>{{contractingPartyName}}</span>
                <span>金额:{{item | filterItemMoney}}</span>
                <el-button type="primary" size="mini" style="float: right;" @click="handleSingleGoods(index)">添加商品</el-button>
                <el-button type="primary" size="mini" style="float: right; margin-right: 10px;" @click="handleSetUnit(index)">批量设置单位</el-button>
              </div>
              <el-table :data="item.invoiceManualGoodsRequestList" border style="width:100%;">
                <el-table-column label="序号" align="center" width="60"  type="index" fixed></el-table-column>
                <el-table-column label="商品" prop="goodsName" align="center"></el-table-column>
                <el-table-column label="数量" prop="num" align="center" width="100">
                  <template slot-scope="scope">
                    <div v-if="scope.row.detailRowStatus !== 1">
                      <el-input v-model="scope.row.num" size="mini" :keyIndex="index" placeholder="请输入数量" @change="handleChangeNum(scope.row)" @focus="hanldeClick(index)"></el-input>
                    </div>
                    <div v-else>{{scope.row.num}}</div>
                  </template>
                </el-table-column>
                <el-table-column label="单价" prop="price" align="center" width="80"></el-table-column>
                <el-table-column label="不含税金额" prop="invoiceAmount" align="center" width="100"></el-table-column>
                <el-table-column label="税率" prop="taxRate" align="center" width="60"></el-table-column>
                <el-table-column label="税额" prop="tax" align="center" width="80"></el-table-column>
                <el-table-column label="单位" prop="unit" align="center" width="120">
                  <template slot-scope="scope">
                    <div  v-if="scope.row.detailRowStatus !== 1">
                      <el-input v-model="scope.row.unit" size="mini" placeholder="请输入单位" @change="handleChangeUnit(scope.row)" @focus="hanldeClick(index)"></el-input>
                    </div>
                    <div v-else>{{scope.row.unit}}</div>
                  </template>
                </el-table-column>
                <el-table-column label="开票含税金额" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.notax" size="mini" v-if="scope.row.detailRowStatus !== 2"  placeholder="请输入金额" @change="handleChange(scope.row)" :clearable="true"></el-input>
                    <span v-else>{{scope.row.notax}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="商品明细状态" align="center">
                  <template slot-scope="scope">
                    {{detailRowStatusTxt[scope.row.detailRowStatus]}}
                   <!-- <el-select v-model="scope.row.detailRowStatus" placeholder="请选择" :disabled="true">
                    <el-option  label="正常" :value="0"></el-option>
                    <el-option  label="折扣行 (负项)" :value="1"></el-option>
                    <el-option  label="被折扣行 (正项)" :value="2"></el-option>
                  </el-select> -->
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" >
                  <template slot-scope="scope">
                    <el-button type="danger" size="mini" @click="handleRemove(index, scope.$index)" v-if="canSave && scope.row.detailRowStatus !== 1">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xl="20">
          <el-form-item label="备注：" prop="remark">
            <el-input type="textarea" v-model="formData.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col  :xs="20" :md="10" :xl="10">
          <el-form-item label="新建人:" prop="createOperator">
            <el-input v-model="formData.createOperator" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
      <el-col :xl="20" v-if="canSave">
          <div style="text-align: center;">
            <el-button type="primary" @click="handleSave" v-loading="submiting">保存</el-button>
            <!-- <el-button plain>取消</el-button> -->
          </div>
        </el-col>
      </el-row>
    </el-form>
    </section>
    <el-dialog  :visible.sync="dialogVisibleGoods" style="width: 100%" top="50px">
       <searchForm :listQuery="listQuery" :queryConfig="queryConfig" :search="search"/>
       <div>
          <el-table :data="list"  border @row-click="clickRow" >
            <el-table-column align="center" width="50">
              <template slot-scope="scope">
                <div style="position: relative;">
                  <label class="input-radio">
                    <input type="radio" :value="{id: scope.row.id, orderId: scope.row.orderId, orderNo: scope.row.orderNo}" v-model="goodsRadio"/>
                    <span></span>
                  </label>
                  <div style="position: absolute;top: 0;left: 0;width:100%;height:100%;z-index: 2;"></div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="订单号" min-width="110" prop="orderNo"></el-table-column>
            <el-table-column align="center" label="收货人姓名" min-width="110" prop="consignee"></el-table-column>
            <el-table-column align="center" label="手机号" min-width="110" prop="mobile"></el-table-column>
            <!-- <el-table-column align="center" label="发票状态" min-width="110" prop="electronicInvoiceStatus"></el-table-column> -->
            <!-- <el-table-column align="center" label="订单状态" >
              <template slot-scope="scope">
                {{states[scope.row.status + '']}}
              </template>
            </el-table-column> -->
            <el-table-column align="center" label="可开商品金额" min-width="110" prop="allowAmount"></el-table-column>
            <el-table-column align="center" label="已开商品金额" min-width="110" prop="alreadyAmount"></el-table-column>
          </el-table>
          <div class="pagination-container" v-if="total > 0">
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page.sync="page"
              :page-size="pageSize"
              :total="total"
            layout="total, prev, pager, next, jumper"></el-pagination>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisibleGoods = false">取 消</el-button>
            <el-button type="primary" @click="handleSure">确 定</el-button>
          </div>
       </div>
    </el-dialog>
    <el-dialog  :visible.sync="dialogVisibleOrderGoods" style="width: 100%" top="50px">
       <div>
          <el-table :data="orderGoods"  border @row-click="handleCheck" >
            <el-table-column align="center" width="50">
              <template slot-scope="scope">
                <div style="position: relative;">
                  <label class="input-checkbox">

                     <input
                      type="checkbox"
                      :value="{
                        goodsId: scope.row.goodsId,
                        goodsSkuId: scope.row.goodsSkuId,
                        goodsName: scope.row.goodsName
                       }"
                      v-model="goodsCheck"/>
                    <span></span>
                  </label>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="id" min-width="110" prop="goodsId"></el-table-column>
            <el-table-column align="center" label="商品" min-width="110" prop="goodsName"></el-table-column>
            <el-table-column align="center" label="单价" min-width="110" prop="price"></el-table-column>
            <el-table-column align="center" label="税率" min-width="110" prop="taxRate"></el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisibleOrderGoods = false">取 消</el-button>
            <el-button type="primary" @click="handleSureAddGoods">确 定</el-button>
          </div>
       </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogVisibleUnit" width = "30%" top="50px">
      <div>
        <el-input  placeholder="请输入内容" v-model="unitTxt" clearable></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleUnit = false">取 消</el-button>
        <el-button type="primary" @click="handleSureUnit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
const regNum = /^(-?\d+)(\.\d+)?$/
import searchForm from '@/components/searchForm/index'
export default {
  components: {
    searchForm
  },
  data() {
    const ruleBase =  [{ required: true, message: '不能为空', trigger: 'change' }]
    return {
      showOrder: false,
      formData: {
        contractingPartyId: '', // 合同签约方id
        createOperator: '', // 新建人
        createSource: 2, // 来源信息 1：app 2：后台
        email: '', // 邮箱
        gmfBankAccount: '', // 银行账号
        gmfOpenBank: '', // 开户银行
        gmfRegisterAddress: '', // 注册地址
        gmfRegisterPhone: '', // 注册电话
        gmfTaxpayerIdentifyNo: '', // 购买方纳税人识别号
        invoiceContent: '商品明细', // 发票内容
        discountFlag: '', // 优惠标识
        invoiceManualMarkRequestList: [
          // {
          //   invoiceManualGoodsRequestList: [
          //     {
          //       goodsId: '',
          //       goodsSkuId: '',
          //       goodsName: '',
          //       goodsNo: '',
          //       invoiceAmount: 0,
          //       num: 0,
          //       price: 0,
          //       tax: 0,
          //       taxRate: 0,
          //       unit: ''
          //     }
          //   ]
          // }
        ],
        invoiceTitle: '', // 发票抬头
        invoiceTitleType: '', // 发票抬头类型 个人/单位
        memberName: '', // 会员名称
        mobile: '', // 手机号
        orderNo: '', // 订单号
        orderPrice: 0, // 订单金额
        remark: '', // 备注
        invoiceTypeTxt: '增值税电子普通发票', //
        couponPrice: 0
      },
      contractList: [], // 合同签约方列表
      rulesBase: {
        'orderNo': ruleBase,
        'memberName': ruleBase,
        'mobile': ruleBase,
        'invoiceTitle': ruleBase,
        'invoiceTitleType': ruleBase,
        'email': ruleBase,
        'invoiceTypeTxt': ruleBase,
        'gmfTaxpayerIdentifyNo': ruleBase,
        'contractingPartyId': ruleBase,
        'createOperator':ruleBase,
        // 'remark':ruleBase,
        // 'gmfBankAccount':ruleBase,
        // 'gmfOpenBank':ruleBase,
        // 'gmfRegisterAddress':ruleBase,
        // 'gmfRegisterPhone':ruleBase
      },
      orderGoods: [],
      dialogVisibleGoods: false,
      listQuery: {
        orderNo: '',
        e3OrderNo: '',
        realName: '',
        userMobile: '',
        consignee: '',
        mobile: '',
        status: 4,
        statusInfo: '',
        type: '',
        electronicInvoiceStatus: '未开票'
      },
      page: 1,
      pageSize: 10,
      total: 0,
      list: [],
      queryConfig: [
        {type: 'input', label: '订单号', prop: 'orderNo', maxlength: 30},
        // {type: 'input', label: '合同号', prop: 'concatNo' },
        {type: 'input', label: '收货人', prop: 'consignee'},
        {type: 'input', label: '手机号', prop: 'mobile' }
      ],
      goodsRadio: {},
      orderPrice: 0,
      invoiceApplyMarkDoList: [], // 开票记录
      orderNo: '',
      orderStatus: '', // 订单状态
      canSave: true,
      dialogVisibleOrderGoods: false, // 订单商品列表
      goodsCheck: [],
      currentTax: -1, // 第几章发票
      submiting: false,
      detailRowStatusTxt: [ '正常', '折扣行 (负项)', '被折扣行 (正项)'],
      unitTxt: '',
      dialogVisibleUnit: false
      // states: {
      //   '1': '待付款',
      //   '2': '待发货',
      //   '3': '待收货',
      //   '4': '已收货',
      //   '5': '已取消',
      //   '6': '付款异常',
      //   '7': '超时取消',
      //   '8': '已退款',
      //   '10': '待发货',
      //   '11': '待成团'
      // },

    }
  },
  computed: {
    contractingPartyName() {
      const index = this.contractList.findIndex(i => i.id === this.formData.contractingPartyId)
      if (index > -1) {
        return this.contractList[index].contractingPartyName
      }
      return '请在上方选择合同签约方'
    },
    // 计算已填优惠金额
    totalMoney() {
      let total = 0
      if (this.formData.invoiceManualMarkRequestList.length > 0)
      this.formData.invoiceManualMarkRequestList.forEach(item => {
        item.invoiceManualGoodsRequestList.forEach(sitem => {
          if (sitem.notax && regNum.test(sitem.notax)) {
             total += parseFloat(sitem.notax)
          }
        })
      })
      return this.filtersMoney(total)
    },
    // 计算填的优惠金额
    countMoney() {
      let total = 0
      if (this.formData.invoiceManualMarkRequestList.length > 0)
      this.formData.invoiceManualMarkRequestList.forEach(item => {
        item.invoiceManualGoodsRequestList.forEach(sitem => {
          if (sitem.notax && regNum.test(sitem.notax) && (sitem.detailRowStatus === 1)) {
            total += parseFloat(sitem.notax)
          }
        })
      })
      return this.filtersMoney(total)
    }
  },
  mounted() {
    this.orderNo = this.$route.query.orderNo
    this.invoiceId = this.$route.query.invoiceId
     if (this.orderNo) {
        this.getOrderDetail()
     }
     if (!this.invoiceId && !this.orderNo) {
       this.showOrder = true
     }
     this.getContractList()
  },
  methods: {
    // 获取订单详情
    getOrderDetail() {
      this.request({
        url: `/invoice-web-manage/invoice/info/order-info/${this.orderNo}`,
        method: 'get',
        params: {
          orderNo: this.orderNo
        }
      }).then(({data}) => {
        this.orderPrice = data.orderPrice
        this.orderGoods = []
        this.formData.invoiceManualMarkRequestList = []
        if (this.invoiceApplyMarkDoList.length > 0) {
          this.invoiceApplyMarkDoList.forEach(i => {
            const invoiceManualGoodsRequestList = []
            i.invoiceApplyGoodsDoList.forEach( ii => {
              const index =  data.orderInvoiceGoodsList.findIndex(iii => iii.goodsSkuId === ii.goodsSkuId)
              let price = this.filtersMoney(ii.price)
              if (index > -1) {
                price = data.orderInvoiceGoodsList[index].price
              }
              const obj = {
                goodsId: ii.goodsId,
                goodsName: ii.goodsName,
                goodsNo: ii.goodsNo,
                invoiceAmount: ii.invoiceAmount,
                presentFlag: ii.presentFlag,
                realityAmount: ii.realityAmount,
                num: ii.num,
                price: price,
                notax:  this.filtersMoney(ii.invoiceAmount + ii.tax),
                tax: ii.tax || 0,
                taxRate: ii.taxRate,
                unit: ii.unit,
                detailRowStatus: ii.detailRowStatus,
                goodsSkuId: ii.goodsSkuId
              }
              invoiceManualGoodsRequestList.push(obj)
              if (this.orderGoods.findIndex(item => item.goodsSkuId === obj.goodsSkuId) === -1) {
                this.orderGoods.push(obj)
              }
            })
            this.formData.invoiceManualMarkRequestList.push({
              invoiceManualGoodsRequestList: invoiceManualGoodsRequestList
            })
          })
        } else {
          let goods = []
          data.orderInvoiceGoodsList.forEach(i => {
            const obj = {
                goodsId: i.goodsId,
                goodsName: i.goodsName,
                goodsNo: i.goodsNo,
                invoiceAmount:  0,
                presentFlag: i.presentFlag,
                realityAmount: i.realityAmount,
                num: i.num,
                price: i.price,
                notax: this.filtersMoney(i.num * i.price),
                tax: 0,
                taxRate: i.taxRate || 0,
                unit: '',
                detailRowStatus: 0,
                goodsSkuId: i.goodsSkuId
            }
            this.getTaxAndInvoiceAmount(obj)
            obj.tax = this.getTaxAndInvoiceAmount(obj).tax
            obj.invoiceAmount = this.getTaxAndInvoiceAmount(obj).invoiceAmount
            this.orderGoods.push(obj)
            // 判断是否优惠标志， 如果是拼凑成两份，一份被折扣行(正项)   折扣行(负项)
            if (data.discountFlag === 1) {
              goods.push({...obj, detailRowStatus: 2})
              // goods.push({...obj, detailRowStatus: 1, notax: '', invoiceAmount: '', tax: '' })
              goods.push({...obj, detailRowStatus: 1 })
            }
          })
          console.log(goods)
          this.formData.invoiceManualMarkRequestList.push({
            invoiceManualGoodsRequestList: goods.length > 0 ? goods : JSON.parse(JSON.stringify(this.orderGoods))
          })
        }
        this.formData.memberName = data.memberName
        this.formData.mobile = data.mobile
        this.formData.orderNo = this.orderNo
        this.formData.orderPrice = data.orderPrice
        this.formData.discountFlag = data.discountFlag
        this.formData.couponPrice = data.couponPrice || 0
        this.orderStatus = data.orderStatus
        this.canEdit()
      }).catch(err => {
        console.log(err)
      })
    },
    // 判断是否可编辑状态
    canEdit(){
      let msg = ''
      if (this.invoiceApplyMarkDoList.length > 0) {
        msg = '该订单已处于开票状态，不能编辑'
      } else if (this.orderStatus < 4 ||this.orderStatus == 10) {
        msg = '该订单尚未确认收货，暂不能手动开票 '
      } else if (this.orderStatus > 4 && this.orderStatus != 10){
        msg = '该订单已取消或已退款，已不支持手动开票 '
      }
      if (msg){
        this.canSave = false
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {console.log(1)}).catch(() => {console.log(1)});

      } else {
        this.canSave = true
      }
      this.avgCountPrice()
    },
    // 合同签约方猎豹
    getContractList() {
      this.request({
        url: `/invoice-web-manage/invoice/contracting-party/search`,
        method: 'post',
        data: {
          enable: 1,
          pageSize: 0
        }
      }).then(({data}) => {
        this.contractList =data.list
        if (this.invoiceId) {
          this.getInvoiceDetail()
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 开票金额改变回调
    handleChange(val){
      if (val.notax === ''){
        return
      }
      if (!regNum.test(val.notax)){
        this.$message.error('金额只能输入数字')
         return
      }
      if (val.detailRowStatus === 1) {
        if (val.notax >= 0) {
          this.$message.error('折扣行 (负项)只能输入负数')
          val.notax = ''
          return
        }

        val.invoiceAmount = this.getTaxAndInvoiceAmount(val).invoiceAmount
        val.tax = this.getTaxAndInvoiceAmount(val).tax
      }
    },
    // 数量改变
    handleChangeNum(val) {
      if (val.detailRowStatus !== 1) {
        val.notax = (val.price *val.num).toFixed(2)
        val.invoiceAmount = this.getTaxAndInvoiceAmount(val).invoiceAmount
        val.tax = this.getTaxAndInvoiceAmount(val).tax
      }
      console.log('inputIndex', this.inputIndex)
      if (this.inputIndex >= 0) {
        const index = this.formData.invoiceManualMarkRequestList[this.inputIndex].invoiceManualGoodsRequestList.findIndex(i => i.goodsSkuId === val.goodsSkuId && i.detailRowStatus === 1)
         console.log('index', index)
        if (index > -1) {
          this.formData.invoiceManualMarkRequestList[this.inputIndex].invoiceManualGoodsRequestList[index].num = val.num
        }
      }
    },
    // 单位改变
    handleChangeUnit(val) {
      if (this.inputIndex >= 0) {
        const index = this.formData.invoiceManualMarkRequestList[this.inputIndex].invoiceManualGoodsRequestList.findIndex(i => i.goodsSkuId === val.goodsSkuId && i.detailRowStatus === 1)
        if (index > -1) {
          this.formData.invoiceManualMarkRequestList[this.inputIndex].invoiceManualGoodsRequestList[index].unit = val.unit
        }
      }
    },
    // 获取点击的索引 -- 代表是哪一个发票
    hanldeClick(index){
      this.inputIndex = index
    },
    // 保存
    handleSave() {
      if (this.submiting) return
      // if (this.formData.orderPrice < this.totalMoney ) {
      //   this.$message.error('已开票金额不能大于可开票金额')
      //   return
      // }
      this.$refs.formBase.validate(val => {
        if (val) {
          let msg = ''
          if (this.formData.invoiceManualMarkRequestList.length === 0) {
            this.$message.error('商品信息不能为空')
            return
          }
          for(let i=0;i<this.formData.invoiceManualMarkRequestList.length;i++){
            const item = this.formData.invoiceManualMarkRequestList[i].invoiceManualGoodsRequestList
            for(let j=0;j<item.length; j++){
              if (item[j].num === '') {
                msg = '请填写数量'
                break
              } else {
                this.formData.invoiceManualMarkRequestList[i].invoiceManualGoodsRequestList[j].num -= 0
              }
              if (!item[j].unit) {
                msg = '请填写单位'
                break
              }
              if (!item[j].notax) {
                msg = '请填写开票金额'
                break
              }
              if(item[j].detailRowStatus === ''){
                msg = '请选择商品明细状态'
                break
              }

            }
            if (msg) {
              break
            }
          }
          if (msg) {
             this.$message.error(msg)
            return
          }
          if(this.formData.invoiceTitleType === '个人'){
            this.formData.gmfBankAccount = ''
            this.formData.gmfOpenBank = ''
            this.formData.gmfRegisterAddress = ''
            this.formData.gmfRegisterPhone = ''
            this.formData.gmfTaxpayerIdentifyNo = ''
          }

          this.$confirm('保存后不能编辑，请仔细检查').then( () =>{
            this.submiting = true
            this.request({
              url: `/invoice-web-manage/invoice/info/manual`,
              method: 'post',
              data: this.formData
            }).then((res) => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '申请成功',
                  onClose: () => {
                    this.submiting = false
                    this.$router.push({
                      path: '/invoive/electronicInvoice/wait'
                    })
                  }
                })
              } else {
                this.submiting = false
              }
            }).catch(err => {
              console.log(err)
              this.submiting = false
            })
          }).catch(e =>{ console.log(e) })

        }
      })
    },
    // 新增一张发票，的商品信息
    handleAddGoods(){
      this.$confirm('请选择需要增加的发票类型', '提示', {
          confirmButtonText: '折扣券发票',
          cancelButtonText: '非折扣发票',
          type: 'warning',
          distinguishCancelAndClose: true,
          center: true
      }).then(() => {
        // 判断是否优惠标志， 如果是拼凑成两份，一份被折扣行(正项)   折扣行(负项)
        const goods = []
        this.orderGoods.forEach(i => {
          goods.push({...i, detailRowStatus: 2})
          // goods.push({...i, detailRowStatus: 1, notax: '', invoiceAmount: '', tax: ''})
          goods.push({...i, detailRowStatus: 1})
        })
        this.formData.invoiceManualMarkRequestList.push({
          invoiceManualGoodsRequestList: goods
        })
        this.avgCountPrice()
      }).catch((e) => {
        if (e === 'cancel') {
          this.formData.invoiceManualMarkRequestList.push({
            invoiceManualGoodsRequestList: JSON.parse(JSON.stringify(this.orderGoods))
          })
        }
      });

    },
    // 移除商品
    handleRemove(index, sindex) {
      // 商品还剩一个且点击的它 删除
      if (sindex === 0 && this.formData.invoiceManualMarkRequestList[index].invoiceManualGoodsRequestList.length === 1) {
        this.formData.invoiceManualMarkRequestList.splice(index, 1)
      } else {
        const detailRowStatus = this.formData.invoiceManualMarkRequestList[index].invoiceManualGoodsRequestList[sindex].detailRowStatus
        if (detailRowStatus === 0) {
          this.formData.invoiceManualMarkRequestList[index].invoiceManualGoodsRequestList.splice(sindex, 1)
        } else if (detailRowStatus === 2){
          this.formData.invoiceManualMarkRequestList[index].invoiceManualGoodsRequestList.splice(sindex, 2)
        }
        if(this.formData.invoiceManualMarkRequestList[index].invoiceManualGoodsRequestList.length === 0) {
          this.formData.invoiceManualMarkRequestList.splice(index, 1)
        }
      }
      this.avgCountPrice()
    },
    // 获取订单列表数据
    handleGetOrder(flag) {
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0)'
      });
      this.request({
        url: '/bsnl-order/order/list',
        method: 'get',
        params: {
          offset: this.page,
          limit: this.pageSize,
          ...this.listQuery
        }
      }).then(({rows, total}) => {
        if (!flag) {
          this.dialogVisibleGoods = true
        }
        loading.close();
        this.list = rows;
        this.total = total;
      }).catch(err => {
        console.log(err);
        this.list = [];
        this.total = 0;
      });
    },
    // 切换分页
    handleCurrentChange(page) {
      this.page = page;
      this.handleGetOrder(true);
    },
    // 订单搜索
    search(){
      this.handleCurrentChange(1)
    },
    // 点击单行选择
    clickRow(item){
      console.log(item)
      this.goodsRadio = {}
      if (item.status === 4 && item.electronicInvoiceStatus === '未开票' ) {
        this.goodsRadio = {
          id: item.id,
          orderId: item.orderId,
          orderNo: item.orderNo
        }
      } else {
        this.$message.warning('此订单无法申请发票')
      }

    },
    // 确认回调
    handleSure() {
      if(!this.goodsRadio.orderNo){
        this.$message.error('请选择订单')
        return
      }
      this.orderNo = this.goodsRadio.orderNo
      this.dialogVisibleGoods = false
      this.getOrderDetail()
    },
    // 获取编辑开票详情
    getInvoiceDetail(){
       this.request({
        url: `/invoice-web-manage/invoice/info/detail/${ this.invoiceId }`,
        method: 'get',
        params: { invoiceId: this.invoiceId }
      }).then(data => {
       if (data.code === 200){
          this.invoiceApplyMarkDoList = data.data.invoiceApplyMarkDoList || []
          const invoiceApplyInfoDo = data.data.invoiceApplyInfoDo
          this.orderNo = invoiceApplyInfoDo.orderNo
          const index = this.contractList.findIndex(i => i.contractingPartyName === invoiceApplyInfoDo.contractingPartyName)
          if (index > -1) {
            this.formData.contractingPartyId = this.contractList[index].id
          }
          this.formData.email = invoiceApplyInfoDo.email
          this.formData.gmfBankAccount = invoiceApplyInfoDo.gmfBankAccount
          this.formData.gmfOpenBank = invoiceApplyInfoDo.gmfOpenBank
          this.formData.gmfRegisterAddress = invoiceApplyInfoDo.gmfRegisterAddress
          this.formData.gmfRegisterPhone = invoiceApplyInfoDo.gmfRegisterPhone
          this.formData.gmfTaxpayerIdentifyNo = invoiceApplyInfoDo.gmfTaxpayerIdentifyNo
          this.formData.invoiceTitle = invoiceApplyInfoDo.invoiceTitle
          this.formData.invoiceTitleType = invoiceApplyInfoDo.invoiceTitleType
          this.formData.remark = invoiceApplyInfoDo.remark
          this.formData.createOperator = invoiceApplyInfoDo.createOperator || invoiceApplyInfoDo.updateOperator
          this.getOrderDetail()
       }
      }).catch(err => { console.log(err) })
    },
    filtersMoney(val){
      return val.toFixed(2)
    },
    // 每张发票添加商品 任选
    handleSingleGoods(index) {
      this.currentTax = index
      this.goodsCheck = []
      this.dialogVisibleOrderGoods = true
    },
    // 商品选择
    handleCheck(item){
      const index = this.goodsCheck.findIndex(i => i.goodsSkuId === item.goodsSkuId)
      if (index > -1) {
        this.goodsCheck.splice(index, 1)
      } else {
        this.goodsCheck.push({
          goodsId: item.goodsId,
          goodsSkuId: item.goodsSkuId,
          goodsName: item.goodsName
        })
      }
    },
    // 确定添加商品
    handleSureAddGoods() {
      if (this.goodsCheck.length === 0) {
        this.$message.info("请选择要添加的商品")
        return
      }
      let index = -1
      for(let i=0; i < this.goodsCheck.length; i++ ){
        index = this.formData.invoiceManualMarkRequestList[this.currentTax].invoiceManualGoodsRequestList.findIndex(ii => ii.goodsSkuId === this.goodsCheck[i].goodsSkuId)
        if (index > -1){
          break
        }
      }
      if (index > -1) {
        this.$message.info("该发票已存在相同商品，请勿重复添加")
        return
      }
      if (this.formData.invoiceManualMarkRequestList[this.currentTax].invoiceManualGoodsRequestList[0].detailRowStatus !== 0){
        this.addSingleGood(true)
      } else {
        this.addSingleGood(false)
      }
    },
    addSingleGood(flag){
       this.goodsCheck.forEach( i => {
          const index = this.orderGoods.findIndex(ii => ii.goodsSkuId === i.goodsSkuId)
          if (index > -1) {
            const newArr = {
              goodsId: this.orderGoods[index].goodsId,
              goodsName: this.orderGoods[index].goodsName,
              goodsNo: this.orderGoods[index].goodsNo,
              invoiceAmount: this.orderGoods[index].invoiceAmount,
              presentFlag: this.orderGoods[index].presentFlag,
              realityAmount: this.orderGoods[index].realityAmount,
              num: this.orderGoods[index].num,
              price: this.orderGoods[index].price,
              notax: this.orderGoods[index].notax || 0,
              tax: this.orderGoods[index].tax,
              taxRate: this.orderGoods[index].taxRate || 0,
              unit: this.orderGoods[index].unit,
              detailRowStatus: 0,
              goodsSkuId: this.orderGoods[index].goodsSkuId
            }
            // 判断是否优惠标志， 如果是拼凑成两份，一份被折扣行(正项)   折扣行(负项)
            if (flag) {
              this.formData.invoiceManualMarkRequestList[this.currentTax].invoiceManualGoodsRequestList.push({...newArr, detailRowStatus: 2})
              // this.formData.invoiceManualMarkRequestList[this.currentTax].invoiceManualGoodsRequestList.push({...newArr, detailRowStatus: 1, notax: '', invoiceAmount: '', tax: '' })
              this.formData.invoiceManualMarkRequestList[this.currentTax].invoiceManualGoodsRequestList.push({...newArr, detailRowStatus: 1})
              this.avgCountPrice()
            } else {
              this.formData.invoiceManualMarkRequestList[this.currentTax].invoiceManualGoodsRequestList.push(newArr)
            }
          }
        })
        this.dialogVisibleOrderGoods = false
        this.goodsCheck = []
    },
    // 平均优惠券
    avgCountPrice() {
      let couponNum = 0
      if (this.formData.invoiceManualMarkRequestList.length > 0){
        this.formData.invoiceManualMarkRequestList.forEach(item => {
          item.invoiceManualGoodsRequestList.forEach( i => {
            if (i.detailRowStatus === 1) {
              couponNum += 1
            }
          })
        })
        if (couponNum > 0) {
          let avg = 0
          console.log(this.formData.couponPrice, couponNum)
          avg = (this.formData.couponPrice / couponNum) * -1
          console.log(avg.toFixed(2))
          this.formData.invoiceManualMarkRequestList.map(item => {
            item.invoiceManualGoodsRequestList.map( i => {
              if (i.detailRowStatus === 1) {
                i.notax = avg.toFixed(2) - 0
                i.invoiceAmount = this.getTaxAndInvoiceAmount(i).invoiceAmount
                i.tax = this.getTaxAndInvoiceAmount(i).tax
              }
              return i
            })
            return item
          })
        }
      }
    },
    // 计算税额与不含税金额
    getTaxAndInvoiceAmount(val){
      const taxRate = val.taxRate
      const tax = (val.notax - 0) / ( 1 + taxRate) * taxRate
      const invoiceAmount = val.notax - (val.notax - 0) / ( 1 + taxRate) * taxRate
      console.log(tax, invoiceAmount)
      return {
        tax: tax.toFixed(2) - 0,
        invoiceAmount: invoiceAmount.toFixed(2) - 0
      }
    },
    // 批量设置单位
    handleSetUnit(index) {
      this.dialogVisibleUnit = true
      this.unitIndex = index
    },
    handleSureUnit(){
      const unitTxt = this.unitTxt.trim()
      if (!unitTxt) {
        this.$message.error("请输入单位")
        return
      }
      if (this.unitIndex >= 0) {
        this.formData.invoiceManualMarkRequestList[this.unitIndex].invoiceManualGoodsRequestList.map(item => {
          item.unit = unitTxt
          return item
        })
      }

      this.dialogVisibleUnit = false
    }
  },
  filters: {
    filterItemMoney(val){
      let total = 0
      if (val.invoiceManualGoodsRequestList) {
        val.invoiceManualGoodsRequestList.forEach(i => {
          if (i.notax && regNum.test(i.notax)) {
            total += parseFloat(i.notax)
          }
        })
      }
      return total.toFixed(2)
    }
  }
}
</script>
<style scoped lang="scss">
.invoice-container {
  /deep/ .el-form {
    .el-input,
    .el-textarea,
    .el-select,
    .el-date-editor{
      width: 100%;
    }
  }
  /deep/ .el-dialog {
    max-width: 1200px;
  }
  /deep/ .el-pagination__editor.el-input {
    width: 50%;
  }
  .dialog-footer {
    text-align: center;
    padding-top: 20px;
  }
}
.goods-cose-contaner {
  padding: 30px 0 30px 150px;
  .goods-cost-title {
    padding: 10px 0;
    overflow:hidden;
  }
  .btn-s {
    float: right;
    margin-right:30px;
  }
  .goods-cost-table {
    border: 1px solid #EBEEF5;
    padding: 10px;
    margin-bottom: 20px;
  }
  .shop-info {
    color: red;
    font-size: 16px;
    padding: 10px 0 10px 10px;
    overflow: hidden;
    line-height: 28px;
    span {
      padding-right:  60px;
    }
  }
}

</style>
